package gl.android.xmppandroidclient;

import gl.android.xmppandroidclient.server.ChatClient;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class XMPP {
	private static XMPP xmpp;
	private Application application;
	private String accout;
	private String password;

	private XMPP(Application application) {
		this.application = application;
	}

	public synchronized static XMPP getSingleton(Application application) {
		if (xmpp == null) {
			xmpp = new XMPP(application);
		}
		return xmpp;
	}

	private final String ACION_XmppConnectService = "gl.android.xmppandroidclient.server.XmppConnectService";
	private ChatClient mChat;
	private boolean hasBind = false;
	private ServiceConnection serConn = new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
			mChat = null;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			Log.i(this.toString(), "onServiceConnected()...");
			mChat = ChatClient.Stub.asInterface(service);
			try {
				mChat.login(accout, password);
				// mChat.login("geliang@dboomsky.com", "geliang");
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	};

	private synchronized void initXmppServer() {
		if (hasBind) {
			application.unbindService(serConn);
		}
		application.bindService(new Intent(ACION_XmppConnectService), serConn,
				Context.BIND_AUTO_CREATE);
		hasBind = true;
	}

	private synchronized void destoryXmppServer() {
		application.unbindService(serConn);
		hasBind = false;
	}

	public void login(String account, String password) {
		this.accout = account;
		this.password = password;
		initXmppServer();
	}

	public void destory(String account, String password) {
		destoryXmppServer();
	}

	public void sendMsg(String to, String messageBody) throws RemoteException {
		mChat.sendMessage(to, messageBody);
	}
}
